package org.xurui.bsj.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.bsj.protocol.cache.ConcurrentMapCache;
import org.xurui.bsj.protocol.command.CmdCodec;
import org.xurui.bsj.protocol.enums.CommandEnum;
import org.xurui.bsj.protocol.msg.BsjMessage;
import org.xurui.bsj.protocol.msg.BsjMessageBuilder;
import org.xurui.bsj.protocol.utils.ArrayUtils;
import org.xurui.bsj.protocol.utils.BinaryUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 4.2.12.短消息
 */
@Slf4j
public class CmdCodec_SEND_SMS implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.SEND_SMS.name().equals(cmd);
    }

    @Override
    public List<DeviceMessage> parsePayload(BsjMessage payload, FromDeviceMessageContext context) {
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000, SEND_SMS,2,1,0]
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        report.setDeviceId(payload.getHeader().getDeviceNo());
        report.setFunctionId(payload.getHeader().getCmd());
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(payload.getHeader().getOrderNo());
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = payload.getHeader().getOrderNo();
        }
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        String tempBody = payload.getTempBody();
        String[] tempBodyArr = tempBody.split("@");
        //properties.put("header", FastBeanCopier.copy(payload.getHeader(), HashMap::new));
        properties.put("header", payload.getHeader().toMap());
        //应答状态(0=设置成功;1=设置异常;)
        properties.put("responseStatus", ArrayUtils.getStrByIndex(tempBodyArr,0));
        report.setOutput(properties);
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000, SEND_SMS,1,20180528111820,19,1@9890@2@1@0@0@1@今天下午会下大雨，请 记得带伞！]
        /**
         * 报文体格式： 1 短信类型： 0 紧急消息 1通知 2作业3考勤4消费5普通消息
         *            2 消息编号：uuid
         *            3 播报还是屏显：0语音播报1屏幕显示2语音播报并 屏幕显示
         *            4 播报报次数 播报时默认1次，不播报则0，上限三 次
         *            5是否闪烁屏幕或LED：0否 1是
         *            6 是否震动：0否 1是
         *            7 是否响铃：0否 1是 情景模式里是静音，则既不震动也不响铃，如果情景 模式里是响铃则，可以震动响铃，也可以不震动响铃， 已情景模式优先。
         *            8 短信内容 短信内容长度： 200个字符 短信内容编码 UTF-8，与第2部分数据交互实现与约 定保持一致
         */
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String  smsType="";
            if(paramsMap.get("smsType")!=null && !paramsMap.get("smsType").equals("")) {
                smsType=paramsMap.get("smsType").toString();
            }

            String mesNo="";
            if(paramsMap.get("mesNo")!=null && !paramsMap.get("mesNo").equals("")) {
                mesNo=paramsMap.get("mesNo").toString();
            }

            String  broadcastByLed="";
            if(paramsMap.get("broadcastByLed")!=null && !paramsMap.get("broadcastByLed").equals("")) {
                broadcastByLed=paramsMap.get("broadcastByLed").toString();
            }

            String broadcastNum="";
            if(paramsMap.get("broadcastNum")!=null && !paramsMap.get("broadcastNum").equals("")) {
                broadcastNum=paramsMap.get("broadcastNum").toString();
            }

            String  hasLed="";
            if(paramsMap.get("hasLed")!=null && !paramsMap.get("hasLed").equals("")) {
                hasLed=paramsMap.get("hasLed").toString();
            }

            String hasShock="";
            if(paramsMap.get("hasShock")!=null && !paramsMap.get("hasShock").equals("")) {
                hasShock=paramsMap.get("hasShock").toString();
            }
            String  hasRing="";
            if(paramsMap.get("hasRing")!=null && !paramsMap.get("hasRing").equals("")) {
                hasRing=paramsMap.get("hasRing").toString();
            }

            String smsContent="";
            if(paramsMap.get("smsContent")!=null && !paramsMap.get("smsContent").equals("")) {
                smsContent=paramsMap.get("smsContent").toString();
            }


            StringBuffer sb = new StringBuffer();
            sb.append(smsType);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(mesNo);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(broadcastByLed);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(broadcastNum);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(hasLed);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(hasShock);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(hasRing);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(smsContent);

            return BsjMessageBuilder.create().buildBsjFunctionInvoickMessage(m,sb.toString());
        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.SEND_SMS.name(),message);
            }
            return null;
        }

    }
}
